package com.example.chatlogger;

import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.player.AsyncPlayerChatEvent;
import org.bukkit.event.player.PlayerCommandPreprocessEvent;
import org.bukkit.plugin.java.JavaPlugin;

import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.StandardOpenOption;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Set;
import java.util.logging.Level;

public class ChatLogger extends JavaPlugin implements Listener {
    // 使用不可变集合且改为大写常量名
    private static final Set<String> WHISPER_COMMANDS = Set.of("msg", "tell", "w");
    
    // 使用线程安全的DateTimeFormatter代替SimpleDateFormat
    private static final DateTimeFormatter DATE_FORMAT = DateTimeFormatter.ofPattern("yyyy-MM-dd");
    private static final DateTimeFormatter TIME_FORMAT = DateTimeFormatter.ofPattern("HH:mm:ss");
    
    // 添加日志格式常量
    private static final String CHAT_FORMAT = "[%s] [聊天] %s: %s%n";
    private static final String WHISPER_FORMAT = "[%s] [私聊] %s -> %s: %s%n";

    private File logFolder;

    @Override
    public void onEnable() {
        // 创建日志目录
        logFolder = new File(getDataFolder(), "logs");
        if (!logFolder.exists()) {
            logFolder.mkdirs();
        }

        // 注册事件监听器
        getServer().getPluginManager().registerEvents(this, this);
    }

    @EventHandler
    public void onPlayerChat(AsyncPlayerChatEvent event) {
        // 记录普通聊天
        logMessage("聊天", event.getPlayer().getName(), null, event.getMessage());
    }

    @EventHandler
    public void onPlayerCommand(PlayerCommandPreprocessEvent event) {
        String[] parts = event.getMessage().substring(1).split("\\s+", 3);
        if (parts.length < 2) return;

        String command = parts[0].toLowerCase();
        if (WHISPER_COMMANDS.contains(command)) {
            String receiver = parts[1].trim(); // 增加trim()处理用户名前后空格
            if (receiver.isEmpty()) return;    // 增加空接收者检查
            
            String message = parts.length > 2 ? parts[2] : "";
            logMessage("私聊", event.getPlayer().getName(), receiver, message);
        }
    }

    private synchronized void logMessage(String type, String sender, String receiver, String message) {
        try {
            File logFile = new File(logFolder, DATE_FORMAT.format(LocalDateTime.now()) + ".log");
            // 使用Files类提升写入性能
            Files.write(logFile.toPath(), (buildLogEntry(TIME_FORMAT.format(LocalDateTime.now()), 
                type, sender, receiver, message)).getBytes(StandardCharsets.UTF_8),
                StandardOpenOption.CREATE, StandardOpenOption.APPEND);
        } catch (IOException e) {
            getLogger().log(Level.SEVERE, "日志写入失败: " + e.getMessage(), e); // 提升错误级别
        }
    }

    private String buildLogEntry(String time, String type, String sender, String receiver, String message) {
        return receiver != null ? 
            String.format(WHISPER_FORMAT, time, sender, receiver, message) :
            String.format(CHAT_FORMAT, time, sender, message);
    }
}